package client

import (
	"errors"
	"gitee.com/yangzx6606/core/pattern"
	"log"
	"net"
)

type UdpClient struct {
	pattern.AbstractSubject[*Packet]
	remote        string       // 服务器地址
	remoteAddress *net.UDPAddr // 服务端地址，用于发送数据
	local         string       // 本地地址
	conn          net.PacketConn
	isRun         bool // 是否在运行
	maxPacketSize int  // 包最大长度
}

// NewUdpClient 实例化UDP客户端，内部实现了一套拆包组包协议
func NewUdpClient(remote string, local string, maxPacketSize int) *UdpClient {
	return &UdpClient{remote: remote, local: local, maxPacketSize: maxPacketSize}
}

func (c *UdpClient) Open() error {
	addr, err := net.ResolveUDPAddr("udp4", c.remote)
	if err != nil {
		log.Println("解析服务端地址[", c.remote, "]失败:", err)
		return err
	}
	c.remoteAddress = addr
	addr = nil
	if len(c.local) != 0 {
		addr, err = net.ResolveUDPAddr("udp4", c.local)
		if err != nil {
			log.Println("解析本地地址[", c.local, "]失败:", err)
			addr = nil
		}
	}
	c.conn, err = net.DialUDP("udp4", addr, c.remoteAddress)
	if err != nil {
		log.Println("连接服务端[", c.remoteAddress, "]失败")
		return err
	}
	c.isRun = true
	return nil
}

func (c *UdpClient) Write(p *Packet) error {
	if !c.isRun {
		return errors.New("未开始工作")
	}
	_, err := c.conn.WriteTo(p.Data, c.remoteAddress)
	return err
}

func (c *UdpClient) Close() {
	if c.isRun {
		c.isRun = false
		_ = c.conn.Close()
	}
}

func (c *UdpClient) doWork() {
	for c.isRun {

	}
}

func (c *UdpClient) send(data []byte) error {
	if !c.isRun {
		return errors.New("未开始工作")
	}
	_, err := c.conn.WriteTo(data, c.remoteAddress)
	return err
}
